package com.ruoyi.crm.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.excel.utils.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.ruoyi.crm.domain.BusinessOpportunity;
import com.ruoyi.crm.domain.CustomerInfo;
import com.ruoyi.crm.domain.StageEntity;
import com.ruoyi.crm.service.*;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.C;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * 商机列表控制层
 * @author  dxy
 *
 */


@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/prospect")
class BusinessOpportunityController extends BaseController {

    private final IBusinessOpportunityService businessOpportunityService;
    private final IStageService stageService;
    private final ICustomerService customerService;


    @DubboReference
    private RemoteUserService remoteUserService;

    /**
     * 分页查询商机列表
     * @param businessOpportunity
     * @param pageQuery
     * @return
     */

    @SaCheckPermission("prospect:prospectInfo:list")
    @GetMapping("/list")
    public TableDataInfo<BusinessOpportunity> list(BusinessOpportunity businessOpportunity, PageQuery pageQuery) {
        TableDataInfo<BusinessOpportunity> list=businessOpportunityService.selectProspectPageList(businessOpportunity,pageQuery);
        list.getRows().forEach(P->{
           if(P.getStageId()!=null){
            StageEntity stage=stageService.selectStageById(P.getStageId());
            if (stage != null) {
                P.getParams().put("stageName",stage.getStageName());
            }
           }
           if(P.getCustomerId()!=null){
               CustomerInfo customerInfo=customerService.selectCustomerById(P.getCustomerId());
               if (customerInfo != null) {
                   P.getParams().put("customerName",customerInfo.getCustomerName());
               }

           }
           if (P.getUserId()!=null){
               String sysUser=remoteUserService.selectUserNameById(P.getUserId());
               if (sysUser!=null) {
                   P.getParams().put("userName",sysUser);
               }
           }
        });
        return list;

    }

    /**
     * 根据商机列表ID获取详细信息
     *
     * @param prospectId 商机列表ID
     */
    @SaCheckPermission("prospect:prospectInfo:query")
    @GetMapping("/{prospectId}")
    public R<BusinessOpportunity> selectProspectById(@PathVariable Long prospectId) {
        return R.ok(businessOpportunityService.selectProspectById(prospectId));
    }

    /**
     * 新增商机列表
     */
    @SaCheckPermission("prospect:prospectInfo:add")
    @Log(title = "商机列表",businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody BusinessOpportunity businessOpportunity) {
        if (businessOpportunity.getCustomerId() == null) {
            return R.fail("请选择客户名称");
        }
        if(businessOpportunity.getProjectApproveId()==null){
            return R.fail("请选择项目确认方式");
        }
        if (businessOpportunity.getCustomerId() == null) {
            return R.fail("请选择客户联系人");
        }
        return toAjax(businessOpportunityService.insertProspectById(businessOpportunity));

    }


    /**
     * 编辑商机列表
     */
    @SaCheckPermission("prospect:prospectInfo:edit")
    @Log(title = "商机列表",businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> eidt(@Validated @RequestBody BusinessOpportunity businessOpportunity) {
        return toAjax(businessOpportunityService.updateProspectById(businessOpportunity));
    }
    /**
     * 删除商机列表
     */
    @SaCheckPermission("prospect:prospectInfo:remove")
    @Log(title = "商机列表",businessType = BusinessType.DELETE)
    @DeleteMapping("/{prospectId}")
    public R<Void> remove(@PathVariable Long prospectId) {
        return toAjax(businessOpportunityService.deleteProspectById(prospectId));
    }
    /**
     *导出商机列表
     */
    @SaCheckPermission("prospect:prospectInfo:export")
    @Log(title = "商机列表",businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusinessOpportunity businessOpportunity){
        List<BusinessOpportunity> list=businessOpportunityService.selectProspectByList(businessOpportunity);
        List<BusinessOpportunity>  listVo= BeanUtil.copyToList(list,BusinessOpportunity.class);
        ExcelUtil.exportExcel(list, "商机列表数据",BusinessOpportunity.class,response);
    }

    /**
     * 文件上传商机列表
     *
     * @param file 文件
     */
    @SaCheckPermission("prospect:prospectInfo:upload")
    @Log(title = "商机列表文件上传", businessType = BusinessType.INSERT)
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        BusinessOpportunity oss = businessOpportunityService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("prospectId", oss.getProspectId().toString());
        return R.ok(map);
    }

}
